from machine import Pin,Timer
import bluetooth

ble_msg = ""

class ESP32_BLE(object):
    def __init__(self, name):
        # 获取定时器0句柄
 #       self.timer1 = Timer(0)
 #       self.led = Pin(2, Pin.OUT, value=0)
        self.conn_handle = None
        self.name = name
        self.ble = bluetooth.BLE()	#config ble.
        self.ble.active(True)
        self.ble.config(gap_name=name)	#Set the GAP device name
        self.disconnected()
        self.ble.irq(self.ble_irq)	#ble 中断处理
        self.register()		#register service
        self.advertise()		#advertise

    def connected(self):
        print("Peripheral Connected")
#       led.value(1)
#        self.timer1.deinit()

    def disconnected(self):
        print("Peripheral disconnected")
#        self.timer1.init(period=1000, mode=Timer.PERIODIC)

    # 蓝牙中断服务
    def ble_irq(self, event, data):
        
        global ble_msg
        if event == 1:		#ble connected
            self.conn_handle, _, _ = data
            self.connected()
        elif event == 2:		#ble disconnected
            self.advertiser()
            self.disconnected()
        elif event == 3:  	#write attribute
            buffer = self.ble.gatts_read(self.command_handle)
            ble_msg = buffer.decode('UTF-8').strip()
#            print(ble_msg)
            
    def register(self):
#        HR_UUID = bluetooth.UUID(0x180D)
#        HR_CHAR = (bluetooth.UUID(0x2A37), bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY,)
#        HR_SERVICE = (HR_UUID, (HR_CHAR,),)
        service_uuid = bluetooth.UUID('6E400001-B5A3-F393-E0A9-E50E24DCCA9E')
        command_uuid = (bluetooth.UUID('6E400002-B5A3-F393-E0A9-E50E24DCCA9E'),bluetooth.FLAG_WRITE)
        notify_uuid = (bluetooth.UUID('6E400003-B5A3-F393-E0A9-E50E24DCCA9E'), bluetooth.FLAG_READ | bluetooth.FLAG_NOTIFY)
        ble_services = ((service_uuid,(notify_uuid,command_uuid)),)
#        SERVICES = (HR_SERVICE, ble_services,)
#        ((hr,),(self.write_handle, self.rx,), ) = self.ble.gatts_register_services(SERVICES)
        ((self.notify_handle, self.command_handle,),  ) = self.ble.gatts_register_services(ble_services)
        
    def send(self, data):   #notify
#        global ble_msg
#        print(ble_msg)
#        print(self.conn_handle)
        if self.conn_handle is not None:
            self.ble.gatts_notify(self.conn_handle, self.notify_handle, data + '\n')

    def get_rec_cmd(self):
        global ble_msg
        cmd = ble_msg
        ble_msg = ""
        return cmd
    
    def advertise(self):
        name = bytes(self.name, 'UTF-8')
        adv_data = bytearray('\x02\x01\x02', 'UTF-8') + bytearray((len(name) + 1, 0x09), 'UTF-8') + name
        self.ble.gap_advertise(100, adv_data)
